package com.snack.common.configuration;

import java.util.Iterator;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 读取配置文件。
 * 读取配置文件的编码默认为GBK；
 * 当配置文件变更后，会自动重载配置文件。
 * Copyright: Copyright (c) May 5, 2009 1:31:34 PM
 * Company: 北京宽连十方数字技术有限公司
 * Author: JinLei
 * Version: 1.0
 */
class PropertiesFactory {
	private static final Log logger = LogFactory.getLog(PropertiesFactory.class);

	/**
	 * 获得配置对象，通常配置文件都是放在classes目录下。
	 * @param fileName 载入的文件名。
	 * @return 配置对象，读取异常返回null。
	 */
	static PropertiesConfiguration getPropertiesConfiguration(String fileName) {
		PropertiesConfiguration config = null;
		try {
			config = new PropertiesConfiguration();
			config.setEncoding("gbk");
			// 载入配置文件
			config.load(fileName);
			// 设置为自动重载配置文件
			config.setReloadingStrategy(new FileChangedReloadingStrategy());
			Iterator<?> iter = config.getKeys();
			StringBuilder sb = new StringBuilder();
			while (iter.hasNext()) {
				String key = (String) iter.next();
				sb.append(key + " = " + config.getString(key) + "\r\n");
			}
			logger.info("properties file loaded: \r\n" + sb.toString());
		} catch (ConfigurationException ex) {
			logger.error("Initial Configuration failed.", ex);
			config = null;
		}
		return config;
	}
}